package com.bjsxt.controller;

import com.bjsxt.entity.Power;
import com.bjsxt.entity.User;
import com.bjsxt.service.UserServer;
import com.util.IPUtil;
import com.util.MenuUtil;
import com.util.ServletUtil;
import com.util.ValidateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * Created by 苏犇 on 2018/12/21. <br>
 */
@Controller
public class MyController {

    @Autowired
    UserServer userServer;

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    @ResponseBody
    public Map login(String username, String password) {
        Map map = new HashMap();
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password) && !ValidateUtil.isContainSpecialChar(username) & !ValidateUtil.isContainSpecialChar(password)) {
            User user = userServer.login(username, password);
            if (user != null) {
                map.put("result", true);
                HttpServletRequest request = ServletUtil.getRequest();
                user.setIPAddr(IPUtil.getIpAddress(request));
                ServletUtil.getSession().setAttribute("user", user);
            } else
                map.put("msg", "用户名或密码错误");
        } else
            map.put("msg", "错误的输入");
        return map;
    }

    @GetMapping("/tohome")
    public String toHome() {
        return "home";
    }

    @RequestMapping(value = "/getMenu", method = RequestMethod.POST)
    @ResponseBody
    public List getMenu() {
        User user = (User) ServletUtil.getSession().getAttribute("user");
        List<Power> powers = user.getRole().getPowers();
        Iterator<Power> iterator = powers.iterator();
        List<Integer> powerIds = new ArrayList<>();
        while (iterator.hasNext()) {
            Power power = iterator.next();
            Integer powerId = power.getPowerid();
            powerIds.add(powerId);
        }
        List menus = MenuUtil.getMenusWithoutUselessRoot(powerIds);
        return menus;
    }

    @GetMapping("logout")
    public String logout() {
        ServletUtil.getSession().removeAttribute("user");
        return "redirect:/";
    }

    @PostMapping("resetReloginStat")
    @ResponseBody
    public Map resetReloginStat(boolean reset) {
        Map map = new HashMap();
        try {
            if (reset) {
                ServletUtil.getSession().removeAttribute("reLogin");
                map.put("result", true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", false);
        }
        return map;
    }
}
